package com.sgb.kjwl.viewmodel.vehicleManagement;

import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;

import androidx.databinding.ObservableField;
import androidx.lifecycle.MutableLiveData;

import com.sgb.kjwl.api.APIManager;
import com.sgb.kjwl.api.NewAPIManager;
import com.sgb.kjwl.model.entity.self.AddDriverAdress;
import com.sgb.kjwl.model.entity.self.CarInfoEntity;
import com.sgb.kjwl.model.entity.self.LicenceOCREntity;
import com.sgb.kjwl.model.entity.transport.DriverAuthEntity;
import com.sgb.kjwl.model.entity.transport.DriverVerifyEntity;
import com.sgb.kjwl.model.entity.transport.DrivingLicenseOCREntity;
import com.sgb.kjwl.model.entity.user.UserAddressEntity;
import com.sgb.kjwl.repository.HomeRepertory;
import com.sgb.kjwl.utils.AddressHelper;
import com.sgb.kjwl.utils.NumberUtil;
import com.sgb.kjwl.view.ui.activity.vehicleManagement.AddDriverInfoActivity;
import com.swgk.core.base.BaseViewModel;
import com.swgk.core.base.api.ICallBack;
import com.swgk.core.base.model.entity.BaseEntity;
import com.swgk.core.dialog.DialogHelper;
import com.swgk.core.util.MToast;
import com.swgk.core.util.NullableUtil;
import com.swgk.core.util.SharedPreferenceUtil;

import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

import okhttp3.MediaType;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class AddDriverAtvModel extends BaseViewModel {

    public ObservableField<DriverVerifyEntity> filterJson = new ObservableField<DriverVerifyEntity>(new DriverVerifyEntity());
    public ObservableField<UserAddressEntity> userAddressEntity = new ObservableField<>(new UserAddressEntity());
    private AddDriverAdress ldDriverAdress = new AddDriverAdress();
    public MutableLiveData<DrivingLicenseOCREntity> ldOcr = new MutableLiveData<>();
    public MutableLiveData<CarInfoEntity> ldCar = new MutableLiveData<>();
    public MutableLiveData<String> ldMain = new MutableLiveData<>();
    public MutableLiveData<String> ldSub = new MutableLiveData<>();
    public MutableLiveData<String> ldActual = new MutableLiveData<>();

    AddDriverInfoActivity activity;
    HomeRepertory repertory;

    public AddDriverAtvModel(AddDriverInfoActivity addVehicleActivity, HomeRepertory repertory) {
        this.activity = addVehicleActivity;
        this.repertory = repertory;
    }

    public void authDriver(long id,
                           LicenceOCREntity info,
                           String name,
                           String idCard,
                           String fileNumber,
                           String mainDriverLicense, String viceDriverLicense, boolean manualCheck) {
        DialogHelper.showProgressDialog(activity, "加载中...").setCanceledOnTouchOutside(false);
        Map map = new HashMap();
        if (id != 0) {
            map.put("id", id);
        }
        map.put("acquireTime", info.getAcquireTime());
        map.put("imageName", info.getImageName());
        map.put("imageIdCard", info.getImageIdCard());
        map.put("imageFileNumber", info.getImageFileNumber());
        map.put("imageValidityPeriodStart", info.getImageValidityPeriodStart());
        map.put("imageValidityPeriodEnd", info.getImageValidityPeriodEnd());
        map.put("imageDriverSLicenseAuthority", info.getImageDriverSLicenseAuthority());
        map.put("imageQuasiDrivingModels", info.getImageQuasiDrivingModels());
        map.put("name", name);
        map.put("idCard", idCard);
        map.put("fileNumber", fileNumber);
        map.put("mainDriverLicense", mainDriverLicense);
        map.put("viceDriverLicense", viceDriverLicense);
        map.put("manualCheck", manualCheck);
        map.put("provinceName", info.getProvinceName());
        map.put("provinceNo", info.getProvinceNo());
        map.put("cityNo", info.getCityNo());
        map.put("cityName", info.getCityName());
        map.put("districtName", info.getDistrictName());
        map.put("districtNo", info.getDistrictNo());
        map.put("detailAddress", info.getDetailAddress());
        map.put("latitude", info.getLatitude());
        map.put("longitude", info.getLongitude());
        if (ldDriverAdress != null) {
            map.put("ipProvinceNo", ldDriverAdress.getIpProvinceNo());
            map.put("ipProvinceName", ldDriverAdress.getIpProvinceName());
            map.put("ipCityNo", ldDriverAdress.getIpCityNo());
            map.put("ipCityName", ldDriverAdress.getIpCityName());
            map.put("ipDistrictNo", ldDriverAdress.getIpDistrictNo());
            map.put("ipDistrictName", ldDriverAdress.getIpDistrictName());
            map.put("ipLongitude", ldDriverAdress.getIpLongitude());
            map.put("ipLatitude", ldDriverAdress.getIpLatitude());
        }

        NewAPIManager.getInstance().getLogisticsAPI().authDriver(map).enqueue(new Callback<BaseEntity>() {
            @Override
            public void onResponse(Call<BaseEntity> call, Response<BaseEntity> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null || response.body().getState() == null)
                    return;
                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                    activity.addSuccess();
                } else if (response.body().getState().equals(APIManager.RESPONSE_FAIL) && "400".equals(response.body().getCode())) {
                    activity.showRealNameIsDifferentWithOCRInfo(response.body().getMsg());
                } else {
                    MToast.showToast(activity, response.body().getMsg());
                }
            }

            @Override
            public void onFailure(Call<BaseEntity> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
                MToast.showToast(activity, t.getMessage());
            }
        });

    }

    /**
     * 上传图片
     */
    public void uploadFile(Context context, File file, int type) {
        Map<String, RequestBody> photos = new HashMap<>();
        RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
        photos.put("file" + "\"; filename=\"" + "image.jpg\"", requestBody);
        DialogHelper.showProgressDialog(context, null, "文件上传中...", 0, false, null).setCanceledOnTouchOutside(true);
        APIManager.getInstance().getUploadAPI().uploadFile(photos).enqueue(new ICallBack<BaseEntity>() {
            @Override
            public void onSuccess(BaseEntity data) {
                //选择图片类型 1:主页 2:副页 3:车辆45度图
                if (data.getData() == null) {
                    uploadFail(type);
                    return;
                }
                if (type == AddDriverInfoActivity.TYPE_SUB) {
                    ldSub.postValue(data.getData().toString());
                } else if (type == AddDriverInfoActivity.TYPE_ACTUAL) {
                    ldActual.postValue(data.getData().toString());
                }
            }

            @Override
            public void onFail() {
                uploadFail(type);
            }
        });
    }

    /**
     * 上传图片且识别驾驶证主页
     */
    public void uploadFileWithOCR(Context context, File file) {
        Map<String, RequestBody> photos = new HashMap<>();
        RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
        photos.put("file" + "\"; filename=\"" + "image.jpg\"", requestBody);
        DialogHelper.showProgressDialog(context, null, "文件上传中...", 0, false, null).setCanceledOnTouchOutside(true);
        //更换接口
        APIManager.getInstance().getUploadAPI().uploadFile(photos).enqueue(new ICallBack<BaseEntity>() {
            @Override
            public void onSuccess(BaseEntity data) {
                if (data.getData() == null) {
                    uploadFail(AddDriverInfoActivity.TYPE_MAIN);
                    return;
                }
                ldMain.postValue(data.getData().toString());
            }

            @Override
            public void onFail() {
                uploadFail(AddDriverInfoActivity.TYPE_MAIN);
            }
        });
    }

    /**
     * 上传失败
     */
    private void uploadFail(int type) {
        if (type == AddDriverInfoActivity.TYPE_MAIN) {
            ldMain.postValue("");
        } else if (type == AddDriverInfoActivity.TYPE_SUB) {
            ldSub.postValue("");
        } else if (type == AddDriverInfoActivity.TYPE_ACTUAL) {
            ldActual.postValue("");
        }
    }

    //上传图片
    public void uploadMutiFileModel(File file, int type) {
        Map<String, RequestBody> photos = new HashMap<>();
        RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
        photos.put("file" + "\"; filename=\"" + "image.jpg\"", requestBody);
        DialogHelper.showProgressDialog(activity, "文件上传中...").setCanceledOnTouchOutside(false);
        APIManager.getInstance().getUploadAPI().uploadFile(photos).enqueue(new Callback<BaseEntity>() {
            @Override
            public void onResponse(Call<BaseEntity> call, Response<BaseEntity> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null || response.body().getState() == null)
                    return;
                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                    activity.uploadImgSuccess(response.body().getData().toString(), type);
                }
            }

            @Override
            public void onFailure(Call<BaseEntity> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
                MToast.showToast(activity, t.getMessage());
            }
        });
    }

    //获取OCR的识别信息
    public void getOCRLicenceInfo(String mainDriverLicense, String viceDriverLicense) {
        DialogHelper.showProgressDialog(activity, "文件上传中...").setCanceledOnTouchOutside(false);
        NewAPIManager.getInstance().getLogisticsAPI().getOCRLicenceInfo(mainDriverLicense, viceDriverLicense).enqueue(new Callback<BaseEntity<LicenceOCREntity>>() {
            @Override
            public void onResponse(Call<BaseEntity<LicenceOCREntity>> call, Response<BaseEntity<LicenceOCREntity>> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null || response.body().getState() == null) {
                    return;
                }

                if (response.body().getState().equals(APIManager.RESPONSE_FAIL)) {
                    activity.oCRFail();
                }

                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                    if (response.body().getData() == null) {
                        activity.oCRSuccess(new LicenceOCREntity());
                    } else {
                        activity.oCRSuccess(response.body().getData());

                    }
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<LicenceOCREntity>> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
                MToast.showToast(activity, t.getMessage());
            }
        });
    }


    /* 提交数据 */
    public void getDriverAuthData() {
        APIManager.getInstance().getDriverAPI().getDriverAuth(filterJson.get()).enqueue(new Callback<BaseEntity<Object>>() {
            @Override
            public void onResponse(Call<BaseEntity<Object>> call, Response<BaseEntity<Object>> response) {
                String msg = response.body().getMsg();
                if (response.body().getState().equals("ok")) {
                    MToast.showToast(activity, msg);
                    SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.CAR_PUBLISH_NO_DRIVER_AUTHENTICATION, Objects.requireNonNull(filterJson.get()).getCarNumber());
                    Intent intent = new Intent();
                    intent.putExtra("state", 1);
                    activity.setResult(1, intent);
                    activity.finish();
                } else {
                    MToast.showToast(activity, msg);
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<Object>> call, Throwable t) {

            }
        });
    }

    /**
     * 获取定位信息
     */
    public void getLocation(Context context) {
        try {
            AddressHelper.getInstance().getCurrentLocation(context, entity -> {
                if (entity == null) return;
                if (ldDriverAdress == null) return;
                ldDriverAdress.setIpLatitude(entity.getLatitude());
                ldDriverAdress.setIpLongitude(entity.getLongitude());
                ldDriverAdress.setIpProvinceName(entity.getProvince());
                ldDriverAdress.setIpProvinceNo(entity.getProvinceNo());
                ldDriverAdress.setIpCityName(entity.getCity());
                ldDriverAdress.setIpCityNo(entity.getCityNo());
                ldDriverAdress.setIpDistrictName(entity.getDistrict());
                ldDriverAdress.setIpDistrictNo(entity.getDistrictNo());
            });
        } catch (Exception e) {
        }
    }

    /**
     * 行驶证ocr识别
     */
    public void carOcr(Context context) {
        if (ldCar.getValue() == null) return;
        Map<String, Object> map = new HashMap<>();
        map.put("vehicleLicense", ldCar.getValue().getVehicleLicense());
        map.put("drivingLicensePage", ldCar.getValue().getDrivingLicensePage());
        DialogHelper.showProgressDialog(context, "加载中");
        //主页和副页数据
        NewAPIManager.getInstance().getLogisticsAPI().operateAuthOCR(map).enqueue(new ICallBack<BaseEntity<DrivingLicenseOCREntity>>() {
            @Override
            public void onSuccess(BaseEntity<DrivingLicenseOCREntity> data) {
                ldOcr.postValue(data.getData());
            }

            @Override
            public void onFailure(Call<BaseEntity<DrivingLicenseOCREntity>> call, Throwable t) {
                onFail();
                onFinally();
            }

            @Override
            public void onFail() {
//                showOcrErrorDialog(context);
            }
        });
    }

    /**
     * 车辆提交审核
     */
    public void authCar(Context context, String idCard, String name, String mainDriverLicense, String viceDriverLicense) {

        //判断不是人工审核的情况下车牌号是否一致
//        if (ldOcr.getValue() != null && !ldOcr.getValue().isManualCheck()
//                && !ldCar.getValue().getCarNumber().equals(ldCar.getValue().getImageCarNumber())) {
//            showCarNumberErrorDialog(context);
//            return;
//        }
        Map<String, Object> map = new HashMap<>();
        if (ldCar.getValue().getId() != 0) {
            map.put("id", ldCar.getValue().getId());
        }
        //人工审核参数 manualCheck
        if (ldOcr.getValue().isManualCheck()) {
            map.put("manualCheck", true);
        }
        map.put("authIndex", 0);
        map.put("idCard", idCard);
        map.put("name", name);
        map.put("mainDriverLicense", mainDriverLicense);
        map.put("viceDriverLicense", viceDriverLicense);
        //图片信息
        map.put("vehicleLicense", ldCar.getValue().getVehicleLicense());
        map.put("drivingLicensePage", ldCar.getValue().getDrivingLicensePage());
        map.put("carImage", ldCar.getValue().getCarImage());
        //页面输入框实际参数
        map.put("carNumber", ldCar.getValue().getCarNumber());
        map.put("carlenName", NumberUtil.trim0(ldCar.getValue().getCarLen()));
        map.put("imageApprovedLoadingQuality", ldCar.getValue().getImageApprovedLoadingQuality());
        //  map.put("weight", ldCar.getValue().getWeight());
        //ocr识别参数
        map.put("imageDateOfIssue", ldOcr.getValue().getImageDateOfIssue());
        map.put("imageNatureOfUse", ldOcr.getValue().getImageNatureOfUse());
        map.put("imageIssuingAuthority", ldOcr.getValue().getImageIssuingAuthority());
        map.put("imageSizeL", ldOcr.getValue().getImageSizeL());
        map.put("imageSizeW", ldOcr.getValue().getImageSizeW());
        map.put("imageVehicleIdentifier", ldOcr.getValue().getImageVehicleIdentifier());
        map.put("imageTotalMass", ldOcr.getValue().getImageTotalMass());
        map.put("imageRegistrationDate", ldOcr.getValue().getImageRegistrationDate());
        map.put("imageCarNumber", ldOcr.getValue().getImageCarNumber());
        map.put("imageVehicleEnergyType", ldOcr.getValue().getImageVehicleEnergyType());
        map.put("imageCarType", ldOcr.getValue().getImageCarType());
        map.put("imageHolder", ldOcr.getValue().getImageHolder());
        map.put("imageSizeH", ldOcr.getValue().getImageSizeH());
        if (!TextUtils.isEmpty(ldOcr.getValue().getImageNumber())) {
            map.put("imageNumber", ldOcr.getValue().getImageNumber());
        } else {
            map.put("imageNumber", "");
        }
        //添加定位信息
        map.put("imageVehicleAddress", ldCar.getValue().getDetailAddress());
        map.put("imageVehicleCity", ldCar.getValue().getCityName());
        map.put("imageVehicleCityNo", ldCar.getValue().getCityNo());
        map.put("imageVehicleDistrict", ldCar.getValue().getDistrictName());
        map.put("imageVehicleDistrictNo", ldCar.getValue().getDistrictNo());
        map.put("imageVehicleLat", ldCar.getValue().getImageVehicleLat());
        map.put("imageVehicleLon", ldCar.getValue().getImageVehicleLon());
        map.put("imageVehicleProvince", ldCar.getValue().getProvinceName());
        map.put("imageVehicleProvinceNo", ldCar.getValue().getProvinceNo());
        map.put("linkman", ldCar.getValue().getLinkman());
        map.put("linkmanPhone", ldCar.getValue().getLinkmanPhone());
    /*    map.put("longitude", ldCar.getValue().getLongitude());
        map.put("latitude", ldCar.getValue().getLatitude());
        map.put("provinceNo", ldCar.getValue().getProvinceNo());
        map.put("provinceName", ldCar.getValue().getProvinceName());
        map.put("cityNo", ldCar.getValue().getCityNo());
        map.put("cityName", ldCar.getValue().getCityName());
        map.put("districtNo", ldCar.getValue().getDistrictNo());
        map.put("districtName", ldCar.getValue().getDistrictName());
        map.put("detailAddress", ldCar.getValue().getDetailAddress());*/
        DialogHelper.showProgressDialog(context, "加载中");
        NewAPIManager.getInstance().getLogisticsAPI().operateDriverAuth(map).enqueue(new ICallBack<BaseEntity<DriverAuthEntity>>() {
            @Override
            public void onSuccess(BaseEntity<DriverAuthEntity> data) {
                //认证成功
//                EventBus.getDefault().post(LogisticsEvent.make().setMessageTag(EventConstant.EVENT_CARINFO_COMMIT));
//                String no = data.getData().getNo();
//                //id不为0则为编辑行驶证，直接返回来源页面
//                if (ldCar.getValue().getId() != 0) {
//                    ((Activity) context).finish();
//                } else {
//                    showSuccessDialog(context, NumberUtil.convertToLong(no));
//                }
            }

            @Override
            public void onFailure(Call<BaseEntity<DriverAuthEntity>> call, Throwable t) {
                //复写失败方法移除父类访问失败逻辑
            }

            @Override
            public void onFailureWithEntity(BaseEntity entity) {
                if ("218".equals(entity.getCode())) {
                    //设置人工审核并重新提交
                    NullableUtil.ofNullable(ldOcr.getValue()).ifPresent(entity1 -> entity1.setManualCheck(true));
                    authCar(context, idCard, name, mainDriverLicense, viceDriverLicense);
                }

                //错误提示弹窗
//                if (entity == null) {
//                    showErrorDialog(context, "接口响应失败");
//                } else if ("217".equals(entity.getCode())) {
//                    showOtherCarNumberDialog(context, entity.getMsg());
//                } else if ("218".equals(entity.getCode())) {
//                    showCarNumberErrorDialog(context, entity.getMsg());
//                } else {
//                    showErrorDialog(context, entity.getMsg());
//                }
                onFinally();
            }
        });
    }

}
